package com.ticket.sass.admin.controller;


import com.alibaba.excel.EasyExcel;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.ticket.sass.admin.annotation.AuthIgnore;
import com.ticket.sass.admin.business.FileUpLoadBusiness;
import com.ticket.sass.admin.business.OrderCardRechargesBusiness;
import com.ticket.sass.admin.dto.input.order.OrderCardRechargeListInput;
import com.ticket.sass.admin.dto.output.order.export.OrderCardRechargesExport;
import com.ticket.sass.admin.dto.output.order.OrderCardRechargesListOutput;
import com.ticket.sass.admin.handler.IdentityInput;
import com.ticket.sass.admin.manager.ThreadLocalIdInputHolderManager;
import com.ticket.sass.admin.model.PageModel;
import com.ticket.sass.admin.model.ResultModel;
import com.ticket.sass.common.exception.enums.ErrorCode;
import com.ticket.sass.common.exception.exception.BadRequestException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ywb
 * @since 2024-03-07
 */
@RestController
@AllArgsConstructor
@ApiSupport(order = 15)
@Api(tags = {"会员卡充值订单数据-模块"})
@RequestMapping("/card-recharge-orders")
public class OrderCardRechargeController {
    final FileUpLoadBusiness fileUpLoadBusiness;
    final OrderCardRechargesBusiness business;
    
    @ApiOperation("列表")
    @GetMapping
    public ResultModel<PageModel<OrderCardRechargesListOutput>> list(
        @Valid OrderCardRechargeListInput input
    ) {
        return ResultModel.success(
            business.list(input)
        );
    }
    
    
    @AuthIgnore
    @ApiOperation("导出")
    @GetMapping("/export")
    public void exportCouponCodes(
        @Valid OrderCardRechargeListInput input,
        HttpServletResponse response,
        @Valid Long cinemaId,
        @Valid String token
    ) throws IOException {
        if (Objects.isNull(cinemaId)){
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                "影院ID不能为空"
            );
        }
        if (!fileUpLoadBusiness.existExportToken(token, "order-recharge")) {
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                "token过期"
            );
        }
        
        // 设置请求参数
        input.setPageNum(1);
        input.setPageSize(1000);
        
        IdentityInput value = ThreadLocalIdInputHolderManager.getValue();
        value.setCinemaId(cinemaId);
        
        ThreadLocalIdInputHolderManager.setValue(value);
        
        // 调用业务逻辑获取数据
        List<OrderCardRechargesListOutput> list = business.list(input).getList();
        
        List<OrderCardRechargesExport> exports = convertToExcelData(list);
        
        // 设置响应头
        // 设置响应头，指定Content-Type和文件名
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(System.currentTimeMillis() + "", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        // 写入数据到Excel文件
        try (OutputStream outputStream = response.getOutputStream()) {
            EasyExcel.write(outputStream, OrderCardRechargesExport.class).sheet("充值订单").doWrite(exports);
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                "导出失败"
            );
        }
    }
    
    
    public List<OrderCardRechargesExport> convertToExcelData(List<OrderCardRechargesListOutput> list) {
        return list.stream().map(this::convert).collect(Collectors.toList());
    }
    
    private OrderCardRechargesExport convert(OrderCardRechargesListOutput output) {
        OrderCardRechargesExport export = new OrderCardRechargesExport();
        
        export.setCardNumber(output.getCardNumber());
        export.setRechargeAmount(output.getRechargeAmount());
        export.setOrderNo(output.getOrderNo());
        export.setCellphone(output.getCellphone());
        export.setCreatedAt(output.getCreatedAt().toString());
        export.setPayPrice(output.getPayPrice());
        
        // 将支付状态和支付类型的整数转换为描述性文本
        export.setPayStatus(convertPayStatusToString(output.getPayStatus()));
        export.setPayTime(output.getPayTime().toString());
        export.setPayType(convertPayTypeToString(output.getPayType()));
        
        return export;
    }
    
    private String convertPayStatusToString(Integer payStatus) {
        // 根据支付状态的枚举值转换为描述性文本
        switch (payStatus) {
            case 0:
                return "未支付";
            case 1:
                return "支付中";
            case 2:
                return "已支付";
            case 3:
                return "支付失败";
            case 4:
                return "已退款";
            default:
                return "未知状态";
        }
    }
    
    private String convertPayTypeToString(Integer payType) {
        // 根据支付类型的枚举值转换为描述性文本
        switch (payType) {
            case 1:
                return "微信支付";
            case 2:
                return "支付宝";
            case 3:
                return "会员卡";
            default:
                return "未知类型";
        }
    }
}
